﻿/*
 * @author: wizardc
 */

using System;
using Dou;
using Dou.Utils;
using DouEditor.Extend;
using UnityEditor;
using UnityEngine.SceneManagement;

namespace DouEditor.Resource
{
    /// <summary>
    /// 调整打包场景中的入口组件的参数
    /// 如：是否是渠道包，是否使用AB加载，是否开启新手引导等等设定
    /// </summary>
    public class BuildStep_SetSceneParam : BuildStepBase
    {
        protected override async void Start()
        {
            var buildStepData = (BuildPackageStepData) _buildStepData;

            if (buildStepData.buildRule.sceneObj == null)
            {
                throw new Exception("构建安装包失败，没有指定构建场景！");
            }
            
            var scenePath = AssetDatabase.GetAssetPath(buildStepData.buildRule.sceneObj);
            var mainScene = await UnitySceneManager.instance.OpenAsync(scenePath);
            var gameMain = GetGameMain(mainScene);

            if (gameMain == null)
            {
                Log.Warning("构建场景缺少继承`AbstractGameMain`实现的组件！");
            }
            else
            {
                gameMain.openSRDebugger = buildStepData.buildRule.openDebugger;
                gameMain.logLevel = buildStepData.buildRule.logLevel;
                gameMain.useAssetBundle = true;
                gameMain.isABEncrypt = buildStepData.buildRule.isEncryptAB;
                
                EditorUtility.SetDirty(gameMain);
                UnitySceneManager.instance.Save(scenePath);
            }
            
            Complete();
        }

        private AbstractGameMain GetGameMain(Scene scene)
        {
            var root = scene.GetRootGameObjects();
            foreach (var go in root)
            {
                var gameMain = go.GetComponent<AbstractGameMain>();
                if (gameMain != null)
                {
                    return gameMain;
                }
            }
            return null;
        }
    }
}
